package com.view;

import java.awt.BorderLayout;
import java.io.File;

import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.tree.DefaultTreeModel;

import com.view.tree.CheckBoxTreeCellRenderer;
import com.view.tree.CheckBoxTreeNode;
import com.view.tree.CheckBoxTreeNodeSelectionListener;

public class LeftTreeView extends JPanel {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private MainView mainView;
	private JTree tree;
	private CheckBoxTreeNodeSelectionListener treeNodeSelectionListener;

	public LeftTreeView(MainView mainView) {
		super();
		this.mainView = mainView;
		init();
	}

	private void init() {
		// 设置根节点
		CheckBoxTreeNode rootNode = new CheckBoxTreeNode("root", "root", "root");
		listNodes("E:\\eclipse-workspace\\3d-cloud\\src", rootNode);
		DefaultTreeModel model = new DefaultTreeModel(rootNode);
		tree = new JTree();
		tree.setModel(model);
		treeNodeSelectionListener = new CheckBoxTreeNodeSelectionListener(mainView, tree);
		tree.addMouseListener(treeNodeSelectionListener);
		tree.setCellRenderer(new CheckBoxTreeCellRenderer());
		JScrollPane scroll = new JScrollPane(tree);
		setLayout(new BorderLayout());
		add(scroll, BorderLayout.CENTER);
	}

	public void expandAll(boolean expand) {
		treeNodeSelectionListener.expandAll(expand);
	}

	//生成所有节点
	public void listNodes(String dir, CheckBoxTreeNode rootNode) {

		File file = new File(dir);
		File[] array = file.listFiles();

		for (int i = 0; i < array.length; i++) {
			if (array[i].isFile()) {
				String name = array[i].getName();
				CheckBoxTreeNode node = new CheckBoxTreeNode(name, name, name);
				rootNode.add(node);
			} else if (array[i].isDirectory()) {
				String name = array[i].getName();
				CheckBoxTreeNode node = new CheckBoxTreeNode(name, name, name);
				rootNode.add(node);
				listNodes(array[i].getPath(), node);
			}
		}
	}
}
